package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;


    /**
     * 新增分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("category:{}", category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /*分页查询*/
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        log.info("[分页成功]");
        /*分页构造器*/
        Page<Category> pageInfo = new Page<>(page, pageSize);
        /*条件构造器*/
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /*修改套餐内容*/
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info("[修改方法执行]");
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }

    @DeleteMapping
    public R<String>delete(long id){
        log.info("[删除数据成功]");
        categoryService.remove(id);
        return R.success("删除方法执行成功");
    }

    /**
     *
     * @param category  传递的参数
     * @return
     */
    @GetMapping("/list")
    //在请求头中获取到的 list
    public R<List<Category>>list (Category category){
        //传递参数 建议用Category  范围大
        log.info("[传递的参数]:{}",category);
        //条件构造器lamb固定表达式
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加条件  获取到的参数不为空  type=1  则为菜品分类   =2  则为套餐
        if(category.getType()!=null){
            lambdaQueryWrapper.eq(Category::getType,category.getType());
        }
       // lambdaQueryWrapper.eq(Category::getType,category.getType());
        //按条件排序
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //将获取到的Service传入到list中
        List<Category>list=categoryService.list(lambdaQueryWrapper);
        //return list
        return R.success(list);
    }





}
